package com.coolwen.service;

import com.alibaba.fastjson.JSON;
import com.coolwen.dao.RoleMapper;
import com.coolwen.dao.RoleResourceMapper;
import com.coolwen.dao.UserMapper;
import com.coolwen.dao.UserRoleMapper;
import com.coolwen.entity.Resource;
import com.coolwen.entity.Role;
import com.coolwen.entity.User;
import com.coolwen.entity.UserRole;
import com.coolwen.util.BeanUtil;
import com.coolwen.util.EndecryptUtils;
import com.coolwen.util.PagedResult;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * 功能概要：UserService实现类
 * Created by user on 2016/6/4.
 */

@Service("userService")
public class UserServiceImpl implements UserService {


    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private UserMapper userDao;


    @Autowired
    private UserRoleMapper userRoleDao;



//    @Override
//    public int delete(long id) {
//        return 0;
//    }

    @Override
    public long delete(long id) {
        return userDao.deleteByPrimaryKey(id);
    }


    @Override
    public long add(User user) {

        User u = EndecryptUtils.md5Password(user);
        userDao.insertSelective(u);
        long id = u.getId();
        return id;
    }

    @Override
    public User add(User user, List<Long> rids) {
        long id = this.add(user);

        //       User u = userDao.selectByPrimaryKey(user.getId());
        for (long rid : rids) {
            UserRole userRole = new UserRole();
            userRole.setUserid(id);
            System.out.println("--------------------------" + id);
            userRole.setRoleid(rid);
            userRoleDao.insertSelective(userRole);
        }
        return user;

    }

    @Override
    public User load(long id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public User loadByUserName(String userName) {
//        User u = userDao.selectUserByUserName(userName);
//        if (u.getLocked() == 0)
//            return null;
        return userDao.selectUserByUserName(userName);
    }

    @Override
    public int update(User record) {
        logger.info("update配置rids:" + JSON.toJSON(record));
 //       userDao.updateByPrimaryKeySelective(record);
        User u = EndecryptUtils.md5Password(record);
        u.setId(record.getId());
        logger.info("update加密配置rids:" + JSON.toJSON(u));
        return userDao.updateByPrimaryKeySelective(u);
    }

    @Override
    public int update(User record, List<Integer> rids) {

        userRoleDao.deleteById(record.getId());
        for (int rid : rids) {
            UserRole ur = new UserRole();
            ur.setUserid(record.getId());
            ur.setRoleid(rid);
            userRoleDao.insertSelective(ur);
        }
        this.update(record);

        return 0;
    }

    @Override
    public List<User> list() {
        return userDao.ListUser();
    }

    @Override
    public User loadUserRole(long uid) {
        return userDao.loadUserRole(uid);
    }

    @Override
    public List<Resource> listUserRes(long uid) {

        return userDao.loadUserRes(uid);
    }

    @Override
    public List<Role> listUserRoles(long uid) {
        User u = this.loadUserRole(uid);

        return u.getRoles();
    }

    @Override
    public List<String> listRoleByUser(long uid) {
        User u = this.loadUserRole(uid);
        List<String> roles = new ArrayList<String>();
        for(Role r:u.getRoles()) {
            roles.add(r.getRole());
        }
        return roles;
    }


    @Override
    public User login(String username, String password) {
        User u = userDao.selectUserByUserName(username);
        if (u == null) throw new UnknownAccountException("用户名或者密码错误!");
        if (!EndecryptUtils.checkMd5Password(username, password, u.getSalt(), u.getPassword()))
            throw new UnknownAccountException("用户名或者密码错误!");

        if (u.getLocked() == 1)
            throw new LockedAccountException("用户已经被锁定");
        return u;
    }

    /**
     * @param userName 查询条件，可为空
     * @param pageNo   查询条件，可为空，默认取1
     * @param pageSize 查询条件，可为空，默认取10
     * @return
     * @author
     * @since 2015年10月23日
     */
//    @Override
//    public PagedResult<User> queryByPage(String userName, Integer pageNo, Integer pageSize) {
//        pageNo = pageNo == null ? 1 : pageNo;
//        pageSize = pageSize == null ? 10 : pageSize;
//        PageHelper.startPage(pageNo, pageSize);  //startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
//        return BeanUtil.toPagedResult(userDao.selectUserSByUserName(userName));
//    }
}
